package com.mock.ems.schedule;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.mock.base.util.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by MOCK on 2017/8/23.
 */
public class QgSchduler {

    private static final Logger logger = LoggerFactory.getLogger(QgSchduler.class);

    public static void schedule() {

        logger.info("qg scheduler start.");
        Executors.newSingleThreadScheduledExecutor()
                .scheduleAtFixedRate(() -> {
                   try {
                       //logger.info("Db.use()==>{},DbPro.MINA==>{}",Db.use(), DbPro.use());
                       List<Record> recordList =  Db.find("select * from limit_buy_activity_config where status != 3");
                       if (CollectionUtil.isNotEmpty(recordList)) {
                           recordList.forEach(item -> handle(item));
                       }
                   }catch (Exception e) {
                       logger.error(e.getMessage(),e);
                   }
                },0,5, TimeUnit.SECONDS);
    }

    private static void handle(Record record) {

        //如果在活动中，则判断是否已经到结束时间
        if (record.getInt("status") == 1) {
            if (new Date().after(record.getDate("end_time"))) {
                record.set("status",3).set("update_time",new Date());
                Db.update("limit_buy_activity_config",record);
            }

            //如果未开始活动，则判断是否已经到开始时间
        }else {
            if (new Date().after(record.getDate("begin_time"))) {
                record.set("status",1).set("update_time",new Date());
                Db.update("limit_buy_activity_config",record);
            }
        }
    }
}
